package com.ruoyi.web.controller.common;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.service.ISysConfigService;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class CaptchaController {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysConfigService configService;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult captchaImage() {
        AjaxResult result = AjaxResult.success();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        result.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled) {
            return result;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        // 生成验证码
        Captcha captcha = null;
        String captchaType = RuoYiConfig.getCaptchaType();
        if ("math".equals(captchaType)) {
            captcha = new ArithmeticCaptcha(130, 48);
        } else if ("char".equals(captchaType)) {
            captcha = new SpecCaptcha(130, 48, 4);
        } else {
            throw new ServiceException("验证码类型配置有误");
        }
        redisCache.setCacheObject(verifyKey, captcha.text(), Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        result.put("uuid", uuid);
        result.put("img", captcha.toBase64());
        return result;
    }
}
